/*
 * =====================================================================================
 *
 *       Filename:  result_cache.h
 *
 *    Description:  result cache class definition.
 *
 *        Version:  1.0
 *        Created:  22/05/2018
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  zhulin, shzhulin3@jd.com
 *        Company:  JD.com, Inc.
 *
 * =====================================================================================
 */

#include "result_cache.h"
#include <sstream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <sys/stat.h>
#include "search_conf.h"
#include "result_cache.h"
#include "log.h"
#include "cachelist_unit.h"
#include "memcheck.h"
#include "data_manager.h"
#include "db_manager.h"
#include "valid_doc_filter.h"

CacheOperator::CacheOperator(
	CPollThread* thread,
	int interval)
	: p_owner_(thread)
{
	this->interval_ = interval;
	if (p_owner_) {
		p_timer_ = p_owner_->GetTimerList(this->interval_);
	}
}

CacheOperator::~CacheOperator()
{ }

int CacheOperator::InitIndex(
	int expired,
	int max_slot)
{
	CCacheListUnit* p_indexcachelist = NULL;
	NEW(CCacheListUnit(p_timer_), p_indexcachelist);
	if (NULL == p_indexcachelist ||
		p_indexcachelist->init_list(max_slot, 0, expired)){
		log_error("init indexcachelist failed");
		return -1;
	}

	p_indexcachelist->start_list_expired_task();
	ValidDocFilter::Instance()->SetCCacheListUnit(p_indexcachelist);
	return 0;
}



UpdateOperator::UpdateOperator(
	CPollThread* thread,
	int interval,
	std::string appFieldFile) 
	: p_owner_(thread)
{
	m_updateTimer = NULL;
	this->interval_ = interval;
	this->m_appFieldFile = appFieldFile;
	if (p_owner_) {
		m_updateTimer = p_owner_->GetTimerList(this->interval_);
	}
} 

void UpdateOperator::TimerNotify(void)
{
	log_error("update table info start");
	FILE * fp = fopen(m_appFieldFile.c_str(), "r");
	if(NULL == fp){
		log_debug("open file[%s] error.", m_appFieldFile.c_str());
		AttachTimer(m_updateTimer);
		return ;
	}
	int fd = fileno(fp);
	struct stat buf;
	fstat(fd, &buf);
	long modifyTime = buf.st_mtime;
	fclose(fp);
	static long lastModifyTime = modifyTime;
	if(modifyTime != lastModifyTime){
		lastModifyTime = modifyTime;
		DBManager::Instance()->ReplaceAppFieldInfo(m_appFieldFile);
	} else {
		log_debug("file[%s] not change.", m_appFieldFile.c_str());
	}
	AttachTimer(m_updateTimer);
	return ;
}

UpdateOperator::~UpdateOperator()
{ }